package com.yunbao.ioc.bd;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * Created by louisyuu on 2020/3/3 下午2:43
 */
public class XmlBeanDefinitionReader {


    private BeanDefinitionRegistry beanDefinitionRegistry;


    public XmlBeanDefinitionReader(BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    public void loadBeanDefinitions(InputStream in) {
        try {
            Document document = new SAXReader().read(in);
            Element rootElement = document.getRootElement();
            List<Element> beanElements = rootElement.selectNodes("//bean");
            beanElements.forEach(ele -> {
                String id = ele.attributeValue("id");
                String className = ele.attributeValue("class");
                BeanDefinition beanDefinition = new BeanDefinition();
                beanDefinition.setId(id);
                beanDefinition.setBeanClassName(className);
                List<Element> propertyElements = ele.selectNodes("property");
                propertyElements.forEach(element -> {
                    String name = element.attributeValue("name");
                    String value = element.attributeValue("value");
                    String ref = element.attributeValue("ref");
                    if (name == null || (value == null && ref == null)) {
                        throw new RuntimeException("Bean id " + id + " has empty property element");
                    }
                    if (value != null && ref != null) {
                        throw new RuntimeException("Bean id " + id + " only can config one value or ref property");
                    }
                    beanDefinition.addPropertyValues(new PropertyValue(name, ref != null ? ref : value, ref != null ? PropertyValue.ValueType.REFERENCE : PropertyValue.ValueType.VALUE));

                });
                beanDefinitionRegistry.registerBeanDefinitions(beanDefinition);
            });
        } catch (DocumentException e) {
            e.printStackTrace();
        }


    }


}
